package com.ldl.exam.service.impl;

import com.ldl.exam.constant.Constants;
import com.ldl.exam.dao.StuMapper;
import com.ldl.exam.dao.UserMapper;
import com.ldl.exam.entity.Stu;
import com.ldl.exam.entity.User;
import com.ldl.exam.entity.UserExample;
import com.ldl.exam.exception.ExamException;
import com.ldl.exam.service.UserService;
import com.ldl.exam.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author liudaolin
 * @version 1.0
 * @date 2022/10/10 22:01:20
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private StuMapper stuMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public void resetPwd(Integer userId, Integer stuId) throws ExamException {
        if(null != userId) {
            User user = new User();
            user.setId(stuId);
            user.setPwd(CommonUtil.md5ToBase64(Constants.DEFAULT_PWD));
            userMapper.updateByPrimaryKeySelective(user);
        }
        if(null != stuId) {
            Stu stu = new Stu();
            stu.setId(stuId);
            stu.setPwd(CommonUtil.md5ToBase64(Constants.DEFAULT_PWD));
            stuMapper.updateByPrimaryKeySelective(stu);
        }
    }

    @Override
    public User login(String loginName, String pwd) throws ExamException {
        UserExample example = new UserExample();
        example.or()
                .andLoginNameEqualTo(loginName)
                .andPwdEqualTo(CommonUtil.md5ToBase64(pwd));
        List<User> list = userMapper.selectByExample(example);
        if(list.isEmpty()) {
            throw new ExamException("用户名或密码错误");
        }
        return list.get(0);
    }
}
